package org.monitor.kit;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

public class FileKit {

	public static void close(Closeable stream){
		if(stream != null){
			try {
				stream.close();
			} catch (IOException e) {
			}
		}
	}
	
	public static boolean deleteAll(File file){
		if(file.exists()){
			if(file.isDirectory()){
				File[] subFiles = file.listFiles();
				for (File subFile : subFiles) {
					deleteAll(subFile);
				}
			}
			return file.getAbsoluteFile().delete();
		}
		return true;
	}
	
	public static String read(File file){
		if(!file.exists()){
			return "";
		}
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String content = null;
			while((content = reader.readLine()) != null){
				sb.append(content).append("\r\n");
			}
		}catch(Exception e){
			
		}finally {
			close(reader);
		}
		return sb.toString();
	}
	
	public static String read(File file, String charset){
		if(!file.exists()){
			return "";
		}
		String content = "";
		if(charset == null || charset.equals("")){
			content = read(file);
		}else {
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(file);
				byte[] bytes = read(fis);
				
				content = new String(bytes, charset);
				
			}catch(Exception e){
			}finally {
				close(fis);
			}
		}
		return content;
	}
	
	public static byte[] read(InputStream is){
		ByteArrayOutputStream bos = null;
		try {
			bos = new ByteArrayOutputStream();
			
			byte[] buffer = new byte[1024];
			int len = -1;
			while((len = is.read(buffer)) != -1){
				bos.write(buffer, 0, len);
			}
			bos.flush();
			
		}catch(Exception e){
		}finally {
			close(bos);
		}
		return bos.toByteArray();
	}
	
}
